package cn.admin.controller;

import cn.admin.config.key.RequestKey;
import cn.admin.config.key.SessionKey;
import cn.admin.config.key.StatusCode;
import cn.admin.entity.Admin;
import cn.admin.entity.Power;
import cn.admin.entity.Role;
import cn.admin.service.AdminService;
import cn.admin.service.PowerService;
import cn.admin.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.List;

/**
 * @Author: 毛苏宇
 * @Description: You can do it!
 * @Date: Create in 11:09 2019/3/23
 */
@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired private AdminService adminService;
    @Autowired private RoleService roleService;
    @Autowired private PowerService powerService;


    /**
     * 去登录
     * @return 登录页面
     */
    @GetMapping("/login")
    public String login(){
        return "/login";
    }



    /**
     * 登录请求
     * @return
     */
    @PostMapping("/login.do")
    @ResponseBody
    public String doLogin(Admin admin, HttpSession session) throws Exception{
        Admin a = adminService.login(admin);
        if (null!=a){
            System.out.println(a);
            session.setAttribute(SessionKey.SESSION_NAME_ADMIN,a);
            List<Power> power = powerService.getPower(a.getAdmin_id());
            session.setAttribute(SessionKey.SESSION_NAME_POWER,power);
            return StatusCode.STATUS_SUCCESS;
        }else{
            return StatusCode.STATUS_FAIL;
        }
    }



    @GetMapping("/add_account")
    public String addAccount(HttpServletRequest request){
        List<Role> roles = roleService.getRoles();
        request.setAttribute(RequestKey.REQUEST_ROLE,roles);
        return "/add_account";
    }


    @PostMapping("/registerAdmin")
    @ResponseBody
    public String registerAdmin(Admin admin){
        boolean b = adminService.adminIsExist(admin.getAdmin_number());
        if (b){
            System.out.println(b);
            return StatusCode.STATUS_EXIST;
        }else {
            admin.setAdmin_register_time(new Timestamp(System.currentTimeMillis()));
            boolean flag = adminService.addAdmin(admin);
            if (flag){
                return StatusCode.STATUS_SUCCESS;
            }else{
                return StatusCode.STATUS_FAIL;
            }
        }
    }


    @RequestMapping("/safeOut")
    public String loginOut(HttpSession session){
        if (null!=session.getAttribute(SessionKey.SESSION_NAME_ADMIN)){
            session.removeAttribute(SessionKey.SESSION_NAME_ADMIN);
        }
        if (null!=session.getAttribute(SessionKey.SESSION_NAME_POWER)){
            session.removeAttribute(SessionKey.SESSION_NAME_POWER);
        }
        return "redirect:login";
    }


}










